package com.collection;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Bag <Item> implements Iterable<Item> {


    private Node<Item> first;
    private int n;

    public static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    public Bag(){
        first = null;
        n = 0;
    }

    public boolean isEmpty() {return first == null;}
    public int size() {return n;}

    public void add(Item item) {
        Node<Item> oldFirst = first;
        first = new Node<>();
        first.item = item;
        first.next = oldFirst;
        n++;
    }

    public Iterator<Item> iterator() {
        return new LinkedIterator(first);
    }

    private class LinkedIterator implements Iterator<Item> {

        private Node<Item> cursor;

        public LinkedIterator(Node<Item> first) {
            this.cursor = first;
        }

        @Override
        public boolean hasNext() {
            return cursor != null;
        }

        @Override
        public Item next() {
            if (!hasNext()) { throw  new NoSuchElementException();}
            Item item = cursor.item;
            cursor = cursor.next;
            return item;
        }
    }

    public static void main(String[] args) {
        Bag<String> bag = new Bag<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            bag.add(item);
        }

        StdOut.println("size of bag = " + bag.size());
        for (String s : bag) {
            StdOut.println(s);
        }
    }

}
